import { Form, Input, message, Modal, Tree, type FormProps, type TreeDataNode, type TreeProps } from "antd";
import { useEffect, useState } from "react";
import type { addAdministratorroleMenus, addAdministratorroleParams, editFace, menuListListFace } from "../../type/administratorrole";
import { addAdministratorrolerole, menuList } from "../../apis/Administratorrole";
import { transformBuildingData } from "../../utils/tree";

interface PropsParams {
    openAdd: boolean;
    refresh: () => void;
    editContent: editFace
}

type FieldType = {
    id?: number;
    menus: addAdministratorroleMenus[];
    name?: string;
};

export default function DiaLog({ openAdd, refresh, editContent }: PropsParams) {
    const [isModalOpen, setIsModalOpen] = useState(openAdd);
    const [form] = Form.useForm(); // 使用 Form.useForm 创建表单实例
    const [menus, setMenus] = useState<menuListListFace[]>([]);
    const [treeData, setTreeData] = useState<TreeDataNode[]>([]);
    const [content, setContent] = useState<menuListListFace[]>([]);

    useEffect(() => {
        if (!isModalOpen) {
            refresh();
        }
    }, [isModalOpen]);
    useEffect(() => {
        console.log(treeData);
         
    }, [treeData]);
    useEffect(() => {
        if (editContent.id) {
            // 确保 form 已经挂载
            form.setFieldsValue({ // 使用 form 实例而不是 ref
                name: editContent.name
            });
            GetContent();
        }else if (!editContent.id){
            // 清除表单数据
            form.resetFields();
        }
    }, [editContent, form]); // 添加 form 作为依赖

    const GetContent = async () => {
        let res = await menuList({ roleid: editContent.id });
        setContent(res.data.list);
    };

    useEffect(() => {
        
        setTreeData(transformBuildingData(content))
    }, [content]); // 添加 form 作为依赖

    useEffect(() => {
        setIsModalOpen(openAdd);
    }, [openAdd]);

    useEffect(() => {
        GetData();
    }, []);

    const GetData = async () => {
        let res = await menuList();
        setMenus(res.data.list);
    };

    useEffect(() => {
        const transformedData = transformBuildingData(menus);
        setTreeData(transformedData);
    }, [menus]);

    const handleCancel = () => {
        setIsModalOpen(false);
        refresh()
    };

    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        editContent.id ? edit(values) : Add(values);
    };

    const edit = async (values: FieldType) => {
        const requestData = {
            ...values,
            id: editContent.id // 将 id 添加到请求数据中
        };
        let res = await addAdministratorrolerole(requestData as addAdministratorroleParams);
        if (res.errCode == 10000) {
            message.success('修改成功');
            refresh();
            form.resetFields(); // 使用 form 实例而不是 ref
        } else {
            message.error('修改失败');
        }
        setIsModalOpen(false);
    };

    const Add = async (values: FieldType) => {
        let res = await addAdministratorrolerole(values as addAdministratorroleParams);
        if (res.errCode == 10000) {
            message.success('添加成功');
            refresh();
            form.resetFields(); // 使用 form 实例而不是 ref
        } else {
            message.error('添加失败');
        }
        setIsModalOpen(false);
    };

    const handleOk = () => {
        form.submit(); // 使用 form 实例而不是 ref
    };

    const onCheck: TreeProps['onCheck'] = (checkedKeys) => {
        const checked = Array.isArray(checkedKeys) ? checkedKeys : checkedKeys.checked;
        form.setFieldsValue({ // 使用 form 实例而不是 ref
            menus: checked.map((item) => {
                return { id: item };
            })
        });
    };

    return (
        <Modal
            title={editContent.id ? '修改角色' : '添加角色'}
            closable={{ 'aria-label': 'Custom Close Button' }}
            open={isModalOpen}
            onOk={handleOk}
            onCancel={handleCancel}
            okText="确认"
            cancelText="取消"
        >
            <Form
                form={form} // 绑定表单实例
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                style={{ maxWidth: 600 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item<FieldType>
                    label="名称"
                    name="name"
                    rules={[{ required: true, message: '请输入角色名称' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item<FieldType>
                    label="权限"
                    name="menus"
                    rules={[{ required: true, message: '请选择权限' }]}
                >
                    <Tree
                        checkable
                        onCheck={onCheck}
                        treeData={treeData}
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
}